package com.lrj.wc;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.AggregateOperator;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.operators.FlatMapOperator;
import org.apache.flink.api.java.operators.UnsortedGrouping;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 *
 * DataSet API
 * @author lrj
 * @date 2022/3/18 14:36
 */
public class BatchWordCount {
    public static void main(String[] args) throws Exception {
        //org.apache.flink.api.java
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
        DataSource<String> stringDataSource = env.readTextFile("input/wc/word.txt");
        FlatMapOperator<String, Tuple2<String, Long>> flatMap = stringDataSource.flatMap((String t, Collector<Tuple2<String, Long>> out) -> {
            String[] strings = t.split("\\s+");
            for (String string : strings) {
                out.collect(new Tuple2<>(string, 1L));
            }
        });
        // 泛型擦除,returns
        FlatMapOperator<String, Tuple2<String, Long>> wordOne = flatMap.returns(Types.TUPLE(Types.STRING, Types.LONG));
        UnsortedGrouping<Tuple2<String, Long>> groupBy = wordOne.groupBy(0);
        AggregateOperator<Tuple2<String, Long>> sum = groupBy.sum(1);
        sum.print();
    }
}
